package com.ml.zookeeper.udline;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务器动态上下线示例
 * 客户端监听
 */
public class DistributeClient {

    private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zk;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        DistributeClient client = new DistributeClient();
        // 1 获取zk连接
        client.getConnect();
        // 2 注册监听，监听/servers下面子节点的增加和删除
        client.getServerList();
        // 3 业务逻辑
        client.business();
    }

    private void getConnect() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, watchedEvent -> {
            try {
                getServerList();
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    private void getServerList() throws KeeperException, InterruptedException {
        List<String> children = zk.getChildren("/servers", true);
        //存储服务器节点主机名称集合
        ArrayList<String> servers = new ArrayList<>();
        for (String child : children) {
            byte[] data = zk.getData("/servers/" + child, false, null);
            servers.add(new String(data));
        }
        //将所有在线主机名称打印到控制台
        System.out.println(servers);
    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }
}
